<template>
  <tl-sub-page render="div" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" @close="close">
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
      <a id="basic" class="step-position">&nbsp;</a>
      <div class="tl-form-line-title">
        立项信息
      </div>
      <el-row style="margin-left:1px">
        <el-col :span="24">
          <el-form-item label="变更原因" prop="changereason" :rules="rules.rulesForInfo">
            <el-input v-model="model.changereason" type="textarea" :rows="5" style="width:100%"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="项目经理" prop="projectmanager">
            <el-input v-model="model.projectmanager" disabled></el-input>
          </el-form-item>
        </el-col> -->
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="项目名称" prop="projectname" :rules="rules.rulesForInfo">
            <el-input v-model="model.projectname"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="项目级别" prop="projectlevel" :rules="rules.rulesForInfo">
            <el-row type="flex">
              <el-select v-model="model.projectlevel" disabled>
                <el-option v-for="item in codeModel.projectlevelList" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
              <el-button type="primary" icon="el-icon-edit-outline" class="levelButton" @click="openChangeLevelDialog" :disabled="!model.projectlevel"></el-button>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目编号" prop="projectnumber">
            <el-input v-model="model.projectnumber" disabled placeholder="系统自动生成"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="计划开始日期" prop="planstartdate" :rules="rules.rulesForInfo">
            <el-date-picker v-model="model.planstartdate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" @change="planStart"> </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划结束日期" prop="planenddate" :rules="rules.rulesForInfo">
            <el-date-picker v-model="model.planenddate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" @change="planEnd"> </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="项目周期" prop="bidcycle">
            <el-input v-model="model.bidcycle" class="unitInput" disabled placeholder="系统自动计算"><template #append>天</template></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目经理" prop="projectmanager">
            <el-input v-model="model.projectmanager" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="Sponsor" prop="sponsorcode" :rules="['2','3'].indexOf(model.projectlevel) >=0 ? [] : rules.rulesForInfo">
            <tl-ref-user v-model="model.sponsorcode" :initDisplayData.sync="model.sponsor" dataType="code" :singleSelect="true" :disabled="disableEditSubmit || disableSave"> </tl-ref-user>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Owner" prop="ownercode" :rules="['2','3'].indexOf(model.projectlevel) >=0 ? [] : rules.rulesForInfo">
            <tl-ref-user v-model="model.ownercode" :initDisplayData.sync="model.owner" dataType="code" :singleSelect="true" :disabled="disableEditSubmit || disableSave"> </tl-ref-user>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row v-if="decisionusernameShow">
        <el-col :span="24">
          <el-form-item label="决策组人员" prop="decisionusername" :rules="rules.rulesForInfo">
            <el-input v-model="model.decisionusername" class="tl-ref-selector" :disabled="true">
              <el-button class="levelButton" slot="append" type="primary" icon="el-icon-search" @click="openMpmProjectResourcePoolDialog"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row v-if="historyLevel && model.projectlevel !== historyLevel">
        <el-col :span="12">
          <el-form-item label="原项目级别">
            <el-input v-model="historyLevel" class="tl-ref-selector" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="model.projectlevel && tempprojectlevel && model.projectlevel !== tempprojectlevel && !(model.purchasepattern === '1' && maxLevel === 3)">
        <el-col :span="24">
          <el-form-item label="项目级别调整原因" prop="changelevelreason" :rules="rules.rulesForInfo">
            <el-input v-model="model.changelevelreason" type="textarea" :rows="4" maxlength="1000" show-word-limit> </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <a id="background" class="step-position">&nbsp;</a>
      <div class="tl-form-line-title">
        项目背景
      </div>
      <el-row>
        <el-col :span="24">
          <el-form-item label="项目背景概述" prop="background">
            <el-input v-model="model.background" type="textarea" :rows="4" maxlength="1000" show-word-limit> </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="项目目标" prop="target">
            <el-input v-model="model.target" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <a id="apply" class="step-position">&nbsp;</a>
      <div class="tl-form-line-title">
        申请信息
      </div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="申请人姓名" prop="username" :rules="rules.rulesForInfo">
            <el-input v-model="model.username" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申请人工号" prop="usercode">
            <el-input v-model="model.usercode" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="申请人部门" prop="applydeptname">
            <el-input v-model="model.applydeptname" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申请人公司" prop="applyorgname">
            <el-input v-model="model.applyorgname" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="float:right; margin-top: 10px">
      <el-button @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="disableSave" icon="el-icon-document-checked" type="primary">保存</el-button>
      <el-button @click="projectSubmit" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval" type="primary">
        <svg-icon icon-class="send" />提交审批
      </el-button>
      <tl-attachment ref="attachmentRef" sourceType="GpmProject" :sourceId="model.id" :disabled="disableAttachment" :editable="stateEdit">
        <el-button type="primary" :disabled="disableAttachment" icon="el-icon-paperclip" @click="$refs.attachmentRef.openUploadDialog()">{{ this.$refs.attachmentRef ? this.$refs.attachmentRef.btnTitle : '' }} [{{ this.$refs.attachmentRef ? (this.$refs.attachmentRef.fileList.length > 0 ? this.$refs.attachmentRef.fileList.length : this.$refs.attachmentRef.fileCount) : 0 }}] </el-button>
      </tl-attachment>
      <el-button type="primary" @click.native="openChangeHistoryDialog('historyList')" v-if="model.id">修改历史</el-button>
      <el-button @click="$refs.history.visible = true" :disabled="disableApprovalHistory" type="primary">
        <svg-icon icon-class="list" />审批历史
      </el-button>
    </div>
    <tl-approval-history ref="history" sourceType="GpmWfForm" :sourceId="model.approvalchangeid ? model.approvalchangeid : 0" />
    <tl-sd-Project-resource-pool-ref ref="sdProjectResourcePoolRef" :title="'决策组选择'" @confirm="getMpmProjectResourceData" :fieldKey="'usercode'" :fieldValue="'username'" :externalSelectedRowKeys="approvalExtraParam === 'LINInvite' ? model.invitedecisionusercode : model.decisionusercode" :isSingleSelect="false" :externalQueryParam="externalDQueryParamForPool" :initDisplayData.sync="LINInviteParam"> </tl-sd-Project-resource-pool-ref>
    <tlChangeLevel-ref ref="changeLevelRef" @confirm="confirmChangeLevel"></tlChangeLevel-ref>
    <change-log-history ref="historyList" topSourceType="GpmProjectHistory" :topSourceId="model.id + ''"></change-log-history>
    <tl-chance-ref ref="chanceRef" @confirm="getChanceNumberData" :externalQueryParam="chanceParam" :isSingleSelect="true" :externalSelectedRowKeys="model.chanceclue"></tl-chance-ref>
    <tl-mpmproject-ref ref="mpmprojectRef" @confirm="getMpmProjectData" :externalQueryParam="mpmprojectParam" :isSingleSelect="true" :externalSelectedRowKeys="model.mpmprojectcode"></tl-mpmproject-ref>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit_edit } from '@/mixins/mixin_approval_edit'
import { mixin_page_fields_custom } from '@/views/gpm/gpmProjectInfo/mixin/mixin_page_fields_custom.js'
/** 子组件 */
import { validateNull } from '@tapui/utils/validate'
import tlChangeLevelRef from '../gpmProject/component/changeLevelCompent'
import tlSdProjectResourcePoolRef from '../gpmProjectResourcePool/refList'
import changeLogHistory from "../gpmProject/component/changeLogHistory"
import tlMpmprojectRef from '../gpmProject/component/mpmSelect'
import tlChanceRef from '../gpmProject/component/chanceSelect'
/** 工具类 */
import { formatDate } from '@tapui/utils/date'
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit_edit, mixin_page_fields_custom],
  // components: { tlsdProjectResourcePoolRef, tlchangeRef, tlChangeLevelRef },
  components: { tlChangeLevelRef, tlSdProjectResourcePoolRef, changeLogHistory, tlMpmprojectRef, tlChanceRef },
  data() {
    var validateForTab = (rule, value, callback) => {
      if (!value) {
        this.tabName = rule.tabname
        return callback(new Error('请输入内容'))
      } else {
        return callback()
      }
    }
    return {
      bidrequired: true,
      moduleTitle: '项目立项',
      urlPrefix: '/sd/projectHistory/',
      url: {
        // 额外的url
        queryOrgByDeptId: '/mpm/projectHistory/queryOrgByDeptId',
        list: '/cbo/approvalNodeIns/list',
        add: '/sd/projectHistory/doSave',
        edit: '/sd/projectHistory/doSave',
        queryCeoInfo: '/sd/projectHistory/queryCeo',
        projectApproval: '/sd/projectHistory/projectChangeApproval',
        approvalList: '/sd/project/approvalList',
        // 更新项目部分字段
        updateProjectPartFields: '/sd/projectHistory/updateProjectPartFields',
        delApproval: '/sd/wfForm/delApproval',
        // 销售项目编号获取
        mpmProjectCode: '/sd/project/mpmProjectCode',
        judgeDecisionUser: '/sd/project/judgeDecisionUser'
      },
      tabName: 'projectbasicinfo',
      sorterInfo: {
        // 排序参数
        sidx: 'id',
        sord: 'desc'
      },
      midChangePoint: true,
      datas: [],
      pageInfo: {
        // 分页参数
        currentPage: 1, // 当前页面
        pageSize: 10, // 每页记录数
        pageSizes: ['10', '50', '100'],
        totalCount: 0 // 总数
      },
      rowKeyStr: 'CODE',
      loading: false,
      visible: false,
      listMode: true,
      externalMQueryParamForPool: {},
      externalDQueryParamForPool: {},
      // 项目立项规则校验重写
      addRules: {
        // 基本信息TAB表单校验
        rulesForInfo: [{ validator: validateForTab, tabname: 'projectbasicinfo', trigger: 'change' }, { required: 'true', message: '请输入内容', trigger: 'change' }],
        // 案例概述TAB表单验证
        rulesForCustomeryInfo: [{ validator: validateForTab, tabname: 'projectcustomerinfo', trigger: 'change' }, { required: 'true', message: '请输入内容', trigger: 'change' }],
        rulesForCompetitorInfo: [{ validator: validateForTab, tabname: 'projectcompetitorinfo', trigger: 'change' }, { required: 'true', message: '请输入内容', trigger: 'change' }]
      },
      // 项目级别默认编码值，根据选择的机会点确定
      tempprojectlevel: '',
      // 项目级别默认显示值，根据选择的机会点确定
      tempdispprojectlevel: '',
      // CEO信息
      tempdecisionusercode: '',
      tempdecisionusername: '',
      mainHeight: 1000,
      // 判断是否是审批组件调用
      fromApproval: '',
      oldprojectlevel: '',
      // 项目等级，例：网级、省级等
      maxLevel: -1,
      // 微前端调用该组件时传递的来源类型
      sourceType: '',
      // 微前端调用时传递的机会点编号
      chancecode: '',
      contractchanged: false,
      projectmodel: {},
      // owner信息
      tempownercode: '',
      tempownername: '',
      chanceParam: {},
      mpmprojectParam: {}
    }
  },
  props: {
    // 当前元素展示方式。默认为dialog，可选div/el-drawer
    render: {
      default: 'el-drawer',
      type: String
    },
    isApprovalCEO: {
      type: String,
      default: ''
    },
    isApprovalPMO: {
      type: String,
      default: ''
    },
    approvalExtraParam: {
      type: String,
      default: ''
    }
  },
  watch: {
    'model.chanceclue'(newVal, oldVal) {
      const param = { chanceclue: newVal }
      if (this.model.sourcetype === '1' && newVal !== null && newVal !== '') {
        getAction(this.url.mpmProjectCode, param).then((res) => {
        if (res.success) {
          if (res.result.projectcode !== null && res.result.projectcode !== undefined && res.result.projectcode !== '') {
            this.$set(this.model, 'mpmprojectcode', res.result.projectcode)
          }
        }
      })
      }
    }
  },
  computed: {
    historyLevel() {
      if (this.model.levelhistory) {
        return JSON.parse(this.model.levelhistory.replace(/\//g, '')).oldprojectlevel
      } else {
        return ''
      }
    },
    LINInviteParam() {
      if (this.approvalExtraParam === 'LINInvite') {
        return this.model.invitedecisionusername
      } else {
        return this.model.decisionusername
      }
    },
    ifOutContractable() {
      if (this.model.outcontractable === '1') {
        return true
      } else {
        return false
      }
    },
     // 决策组成员控制
    decisionusernameShow() {
      if (this.model.approvalprojecttype === '1') {
         return true
      } else if (this.model.decisionusername !== '' && this.model.decisionusername !== undefined && this.model.decisionusername !== null) {
         return true
      } else {
         return false
      }
    }
  },
  methods: {
    openMpmProjectDialog(index) {
      this.mpmprojectParam = {
        deptcode: this.model.deptcode
       }
      this.$refs.mpmprojectRef.visible = true
    },
    openChanceDialog(index) {
      this.chanceParam = {
        deptcode: this.model.deptcode
       }
      this.$refs.chanceRef.visible = true
    },
    getMpmProjectData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'mpmprojectcode', selectKey)
    },
    getChanceNumberData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'chanceclue', selectKey)
    },
    changeSource() {
      if (this.model.ourprocductfund && this.model.ourprocductfund !== '') {
        this.changeOurProductFund('')
      }
      this.$set(this.$refs.custometInfoRef.model, 'customerInfoList', [])
      this.$set(this.model, 'chanceclue', '')
      this.$set(this.model, 'mpmprojectcode', '')
    },
    clearDemandInfo() {
      this.$set(this.model, 'clientdemand', '')
    },
    localClose() {
    },
    changeLevel() {
      if (this.model.sdrange) {
        switch (this.model.sdrange) {
          // 网级交付
          case '1': {
            this.$set(this.model, 'projectlevel', '0')
            this.$set(this.model, 'projectdefaultlevel', '0')
            let tempLevelData = this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel)
            // 若项目默认级别为空则为tempprojectlevel和tempdispprojectlevel赋值
            this.tempprojectlevel = this.model.projectlevel
            this.tempdispprojectlevel = tempLevelData.name
            break
          }
          // 地电、省级交付
          case '2':
          case '3': {
            if (this.model.ourprocductfund) {
              let fund = parseFloat(this.model.ourprocductfund)
              if (fund >= 500) {
                this.$set(this.model, 'projectlevel', '0')
                this.$set(this.model, 'projectdefaultlevel', '0')
                let tempLevelData = this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel)
                // 若项目默认级别为空则为tempprojectlevel和tempdispprojectlevel赋值
                this.tempprojectlevel = this.model.projectlevel
                this.tempdispprojectlevel = tempLevelData.name
                break
              } else if (fund >= 100) {
                this.$set(this.model, 'projectlevel', '1')
                this.$set(this.model, 'projectdefaultlevel', '1')
                let tempLevelData = this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel)
                // 若项目默认级别为空则为tempprojectlevel和tempdispprojectlevel赋值
                this.tempprojectlevel = this.model.projectlevel
                this.tempdispprojectlevel = tempLevelData.name
                break
              } else {
                this.$set(this.model, 'projectlevel', '2')
                this.$set(this.model, 'projectdefaultlevel', '2')
                let tempLevelData = this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel)
                // 若项目默认级别为空则为tempprojectlevel和tempdispprojectlevel赋值
                this.tempprojectlevel = this.model.projectlevel
                this.tempdispprojectlevel = tempLevelData.name
                break
              }
            } else {
              this.$set(this.model, 'projectlevel', '2')
              this.$set(this.model, 'projectdefaultlevel', '2')
              let tempLevelData = this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel)
              // 若项目默认级别为空则为tempprojectlevel和tempdispprojectlevel赋值
              this.tempprojectlevel = this.model.projectlevel
              this.tempdispprojectlevel = tempLevelData.name
              break
            }
          }
          // 市县级/非电交付
          case '4':
          case '5': {
            if (this.model.ourprocductfund) {
              let fund = parseFloat(this.model.ourprocductfund)
              if (fund >= 500) {
                this.$set(this.model, 'projectlevel', '1')
                this.$set(this.model, 'projectdefaultlevel', '1')
                let tempLevelData = this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel)
                // 若项目默认级别为空则为tempprojectlevel和tempdispprojectlevel赋值
                this.tempprojectlevel = this.model.projectlevel
                this.tempdispprojectlevel = tempLevelData.name
                break
              } else if (fund >= 100) {
                this.$set(this.model, 'projectlevel', '2')
                this.$set(this.model, 'projectdefaultlevel', '2')
                let tempLevelData = this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel)
                // 若项目默认级别为空则为tempprojectlevel和tempdispprojectlevel赋值
                this.tempprojectlevel = this.model.projectlevel
                this.tempdispprojectlevel = tempLevelData.name
                break
              } else {
                this.$set(this.model, 'projectlevel', '2')
                this.$set(this.model, 'projectdefaultlevel', '2')
                let tempLevelData = this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel)
                // 若项目默认级别为空则为tempprojectlevel和tempdispprojectlevel赋值
                this.tempprojectlevel = this.model.projectlevel
                this.tempdispprojectlevel = tempLevelData.name
                break
              }
            } else {
              this.$set(this.model, 'projectlevel', '2')
              this.$set(this.model, 'projectdefaultlevel', '2')
              let tempLevelData = this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel)
              // 若项目默认级别为空则为tempprojectlevel和tempdispprojectlevel赋值
              this.tempprojectlevel = this.model.projectlevel
              this.tempdispprojectlevel = tempLevelData.name
              break
            }
          }
        }
      }
    },
    // 更新机会点编号
    changeChanceClue(val) {
      this.$set(this.model, 'chanceclue', val)
    },
    // 更新可参与金额
    changeOurProductFund(val) {
      this.$set(this.model, 'ourprocductfund', val)
      this.changeLevel()
    },
    // 更新是否包含外包字段
    changeOutContractable(val) {
      this.$set(this.model, 'outcontractable', val)
    },
    changeContract(isrequired) {
      this.contractchanged = isrequired
    },
    doSubmitEdit() {
      if (!this.beforeSubmit()) {
        return
      }
      if (this.isAdd) {
        this.doAdd()
      } else {
        this.doEdit()
      }
    },
    beforeSubmit() {
      let copymodel = {}
      Object.assign(copymodel, this.model)
      this.$set(this.model, 'basicInfo', copymodel)
      return true
    },
    changepurchasepattern(value) {
      if (value === '8') {
        this.bidrequired = false
      } else {
        this.bidrequired = true
      }
      // 判断是否为省级，省级电商化采购等级固定为B
      if (value === '1' && this.maxLevel === 3) {
        this.$set(this.model, 'projectlevel', '1')
      }
    },
    planStart(e) {
      if (this.model.planenddate) {
        var a = new Date(this.model.planstartdate).getTime()
        var b = new Date(this.model.planenddate).getTime()
        if (a > b) {
          this.$tap.alert('开始日期不得大于结束日期。', 'warning')
          this.$set(this.model, 'planstartdate', '')
          this.$set(this.model, 'bidcycle', '')
          return
        } else {
          var t = b - a
          var days = Math.ceil(t / (1000 * 3600 * 24)) + 1
          this.$set(this.model, 'bidcycle', days)
        }
      }
    },
    planEnd(e) {
      if (this.model.planstartdate === '' || typeof this.model.planstartdate === 'undefined') {
        this.$tap.alert('请先选择计划开始日期！', 'warning')
        this.$set(this.model, 'planenddate', '')
        this.$set(this.model, 'bidcycle', '')
        return
      }
      var c = new Date(this.model.planenddate).getTime()
      var d = new Date(this.model.planstartdate).getTime()
      if (c < d) {
        this.$tap.alert('开始日期不得大于结束日期。', 'warning')
        this.$set(this.model, 'planenddate', '')
        this.$set(this.model, 'bidcycle', '')
        return
      }
      var a = c - d
      var days = Math.ceil(a / (1000 * 3600 * 24)) + 1
      this.$set(this.model, 'bidcycle', days)
    },
    assignDefaultValue() {
      if (this.isAdd) {
        this.model = JSON.parse(JSON.stringify(this.projectmodel))
        this.model.projectid = this.model.id
        this.model.state = 0
        this.$set(this.model, 'projectdefaultlevel', this.projectmodel.projectlevel)
        delete this.model.id
        console.log(this.model)
      }
    },
    projectSubmit() {
      let that = this
      const basicInfoValidate = new Promise(function (resolve, reject) {
        that.$refs.form.validate((valid, res) => {
          if (valid) {
            resolve()
          } else {
            reject("按要求填写表单数据项，包括必填项，数据格式等")
          }
        })
      })
      that.submitLoading = true
      Promise.all([basicInfoValidate]).then(async () => {
        let saveresult = await that.addBase()
        if (saveresult) {
          this.saveLoading = true
          const parameter = this.model
          putAction(this.url.projectApproval, parameter)
            .then((res) => {
              if (res.success) {
                this.queryData(that.model.id).then((_) => {
                  this.loaded()
                  this.saveLoading = false
                  this.submitLoading = false
                })
                this.$tap.alert('提交审批成功', 'success')
              } else {
                this.$tap.alert(res.message, 'warning')
                this.saveLoading = false
                this.submitLoading = false
              }
            })
            .catch((err) => {
              this.saveLoading = false
              this.submitLoading = false
            })
        }
      }).catch((error) => {
        this.$tap.alert(error)
        that.submitLoading = false
      })
    },
    /** 执行编辑提交 */
    doEdit() {
      this.saveLoading = true
      putAction(this.url.edit, this.model)
        .then((res) => {
          if (res.success) {
            this.$tap.message(res.message, 'success')
            this.$emit('refresh')
            this.$emit('loaded', this.model)
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    // 选择项目所属部门
    onSelectDept(selectedDepts) {
      const selectedDept = selectedDepts[0]
      const { id, code, fullname } = selectedDept
      this.$set(this.model, 'deptcode', code)
      this.$set(this.model, 'deptname', fullname)
      const param = {
        deptId: id
      }
      getAction(this.url.queryOrgByDeptId, param).then((res) => {
        if (res.success) {
          const { code: orgcode, name: orgname } = res.result
          this.$set(this.model, 'orgcode', orgcode)
          this.$set(this.model, 'orgname', orgname)
        } else {
          this.$tap.alert('已选部门关联公司信息错误，请联系系统管理员')
        }
      })
    },
    /** 抽屉组件必重写，主要为了执行resizeHandler方法、给mainScrollElement赋值，并添加监听事件，不要直接复制该方法 **/
    open() {
      this.model = {}
      this.contractchanged = false
      this.resizeHandler()
      this.$nextTick(async () => {
        await this.getFieldsCustomSetting('sdProjectEdit', 'el-form')
        this.$refs.form.clearValidate()
        if (this.isAdd === true) {
          this.title = '新增' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          this.queryCeoInfo(this.user.code)
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then((_) => {
              this.assignDefaultValue()
              this.$refs.form.clearValidate()
              this.loaded()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
            this.loaded()
          }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            // 获取项目等级
            this.$refs.form.clearValidate()
            // this.getMaxLevel()
            this.queryCeoInfo(this.model.projectmanagercode)
            this.loaded()
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            // 获取项目等级
            this.$refs.form.clearValidate()
            this.queryCeoInfo(this.model.projectmanagercode)
            // this.getMaxLevel()
            this.loaded()
          })
        }
      })
      this.datas = []
    },
    // 查询决策组成员信息
    queryCeoInfo(managercode) {
      let params = {
        managercode: managercode
      }
      let that = this
      getAction(that.url.queryCeoInfo, params).then((res) => {
        if (res.success) {
          let code = []
          let name = []
          res.result.forEach((element) => {
            code.push(element.code)
            name.push(element.name)
            if (element.description === 'sdprovince') {
              that.tempownercode = element.code
              that.tempownername = element.name
            }
          })
          let codes = ',' + code.join(',') + ','
          let names = name.join(',')
          // 将CEO信息存到中间变量中
          that.tempdecisionusercode = codes
          that.tempdecisionusername = names
        }
      })
    },
    // 项目级别变更后，清空项目经理和决策组--2-7todo 暂时取消
    clear() {
      if (this.model.projectmanagercode || this.model.decisionusercode) {
        this.$set(this.model, 'projectmanagercode', '')
        this.$set(this.model, 'projectmanager', '')
        this.$set(this.model, 'decisionusercode', '')
        this.$set(this.model, 'decisionusername', '')
      }
    },
    /** 打开决策组成员参照 */
    openMpmProjectResourcePoolDialog() {
      const { projectlevel, projecttype } = this.model
      if (!projectlevel) {
        this.$tap.alert('请先选择项目级别！', 'warning')
        this.$refs.sdProjectResourcePoolRef.visible = false
      } else {
        this.externalDQueryParamForPool = {
          qry_projectlevel: projectlevel,
          projecttype: projecttype
        }
        this.$refs.sdProjectResourcePoolRef.visible = true
      }
    },
    /** 获取决策组成员参照数据 */
    getMpmProjectResourceData(selectionRow, selectKey, selectionValue) {
          // 如果是ABC级项目
          let resultcodes = ''
          let resultnames = ''
          if (Array.isArray(selectionRow)) {
            if (selectionRow.length > 0) {
              let code = []
              let name = []
              selectionRow.forEach((element) => {
                code.push(element.usercode)
                name.push(element.username)
              })
              resultcodes = code.join(',')
              // resultcodes = codes ? ',' + codes + ',' : ''
              resultnames = name.join(',')
            }
          } else {
            resultcodes = ',' + selectionRow.usercode + ','
            resultnames = selectionRow.username
          }
          this.$set(this.model, 'decisionusercode', resultcodes)
          this.$set(this.model, 'decisionusername', resultnames)
    },
    /** 打开机会点参照 */
    openChanceclueDialog() {
      if (!this.model.sourcetype) {
        this.$tap.alert('请先选择项目来源！', 'warning')
      } else {
        this.$refs.contractRef.visible = true
      }
    },
    /** 执行新增提交 */
    doAdd() {
      this.saveLoading = true
      // 增加唯一单号
      this.$set(this.model, 'billuid', this.uid)
      postAction(this.url.add, this.model)
        .then((res) => {
          if (res.success) {
            this.$tap.message('添加成功', 'success')
            this.queryData(res.result.id).then((_) => {
              this.loaded()
            })
            this.isAdd = false
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          // this.afterSubmit()
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    // 数据库字符串对象去特殊字符
    loaded() {
      this.$emit('loaded', this.model)
      // 林总审批用
      this.oldprojectlevel = this.model.projectlevel
      // 给midChangePoint赋初始值
      if (this.model.chanceclue) {
        this.midChangePoint = this.model.chanceclue.split(',') <= 1
      }
      // 若为不可编辑状态则清空placeholder
      if (this.disableEditSubmit || this.disableSave) {
        this.$refs.form.fields.forEach(item => {
          if (item.$children[1].$options._componentTag === "el-input") {
            item.$children[1].getInput().placeholder = ''
          }
        })
      }
    },
    close() {
      this.tempprojectlevel = ''
      this.tempdispprojectlevel = ''
      this.maxLevel = -1
    },
    /** 打开调整项目级别的弹框 **/
    openChangeLevelDialog() {
      this.$refs.changeLevelRef.projectlevelList = this.codeModel.projectlevelList
      this.$refs.changeLevelRef.dispprojectdefaultlevel = this.codeModel.projectlevelList.find((item) => item.code === this.model.projectdefaultlevel).name
      this.$set(this.$refs.changeLevelRef.model, 'projectlevel', this.model.projectlevel)
      this.$set(this.$refs.changeLevelRef.model, 'dispprojectlevel', this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel).name)
      this.$set(this.$refs.changeLevelRef.model, 'changelevelreason', this.model.changelevelreason)
      this.$refs.changeLevelRef.visible = true
    },
    /** 填写调整项目等级原因后回写数据 **/
    confirmChangeLevel(data) {
      this.$set(this.model, 'projectlevel', data.projectlevel)
      this.$set(this.model, 'changelevelreason', data.changelevelreason)
      this.$set(this.model, 'decisionusercode', '')
      this.$set(this.model, 'decisionusername', '')
    },
    afterSubmit() {
      this.loaded()
    },
    /** 抽屉组件必有 **/
    resizeHandler() {
      this.mainHeight = document.body.getBoundingClientRect().height - 100 - (this.isApproval ? 110 : 0)
    },
    /** 抽屉组件必有 **/
    doCancelEdit() {
      this.visible = false
      this.$emit('close')
      this.$emit('refresh')
    },
    /** 抽屉组件必有 **/
    formatDate(date) {
      return formatDate(new Date(date), 'yyyy-MM-dd')
    },
    openMeetDialog(val, editForm) {
      if (val === '1') {
        window.open('https://meet.topscomm.com/meet/meetManage')
      }
    },
    // 审批专用函数
    beforeApproval(resolve, reject) {
      // PMO标准化审批
      if (this.uiOperateState === 3) {
        let that = this
        if (that.isApprovalPMO !== '' && (that.model.pmoapprovaltype === '' || that.model.pmoapprovaltype === null)) {
          reject("请填写审批类型")
        }
        const basicInfoValidate = new Promise(function (resolve, reject) {
          that.$refs.form.validate((valid, res) => {
            if (valid) {
              resolve()
            } else {
              reject("按要求填写表单数据项，包括必填项，数据格式等")
            }
          })
        })
        that.submitLoading = true
        let promiseArr = [basicInfoValidate]
        Promise.all(promiseArr).then(async () => {
          let saveresult = await that.addBase()
          if (saveresult) {
            that.submitLoading = false
            resolve('保存成功')
          } else {
            that.submitLoading = false
            reject('保存失败')
          }
        }).catch((error) => {
          this.$tap.alert(error)
          that.submitLoading = false
          reject('保存失败')
        })
      } else if (this.isApprovalCEO !== '' || 'LINInvite' === this.approvalExtraParam || 'LIN' === this.approvalExtraParam) {
        let paraMap = {
          id: this.model.id
        }
        if (this.isApprovalCEO !== '') {
          paraMap.approvaltype = this.model.approvaltype
        } else if ('LINInvite' === this.approvalExtraParam) {
          const { decisionusercode, invitedecisionusercode, projectlevel } = this.model
          if (projectlevel === '' || projectlevel === undefined) {
            reject('请选择项目级别！')
            return
          } else {
            paraMap.projectlevel = projectlevel
            paraMap.invitedecisionusercode = invitedecisionusercode
            paraMap.invitedecisionusername = this.model.invitedecisionusername
            let flag = false
            let decisionusercodeArray = decisionusercode.split(',')
            if (invitedecisionusercode && invitedecisionusercode !== '') {
              let invitedecisionusercodeArray = invitedecisionusercode.split(',')
              flag = decisionusercodeArray.find((item) => (item ? invitedecisionusercodeArray.indexOf(item) >= 0 : false))
            }
            if (flag) {
              reject('邀请决策的人员和原决策组人员重复，请重新选择！')
              return
            } else {
              // 把邀请决策的人员添加进原决策组人员
              if (invitedecisionusercode && invitedecisionusercode !== '') {
                this.model.decisionusercode = this.model.decisionusercode + this.model.invitedecisionusercode.substring(1)
                this.model.decisionusername = this.model.decisionusername + ',' + this.model.invitedecisionusername
                paraMap.decisionusercode = this.model.decisionusercode
                paraMap.decisionusername = this.model.decisionusername
              }
            }
          }
        } else if ('LIN' === this.approvalExtraParam) {
          const { projectlevel } = this.model
          if (projectlevel === '' || projectlevel === undefined) {
            reject('请选择项目级别！')
            return
          } else {
            paraMap.projectlevel = projectlevel
          }
        }
        if (this.model.projectlevel !== this.oldprojectlevel) {
          paraMap.oldprojectlevel = this.oldprojectlevel
        }
        putAction(this.url.updateProjectPartFields, paraMap)
          .then((res) => {
            if (res.success) {
              resolve()
            }
          })
          .catch((error) => {
            this.$tap.alert(error, 'warning')
            reject(error)
          })
      }
    },
    openChangeHistoryDialog(historyList) {
      /** 打开详情对话框实现*/
      this.$refs[historyList].visible = true
    },
    openContractDialog(index) {
      this.$refs.contractRef.visible = true
    },
    getContractNumberData(selectionRow, selectKey, selectionValue) {
      // 判断是否选择机会点编号不同的机会点
      // let selectionSet = []
      // for (let i = 0; i < selectionRow.length; i++) {
      //   if (selectionSet.indexOf(selectionRow[i].chancecode) === -1) {
      //     selectionSet.push(selectionRow[i].chancecode)
      //   }
      // }
      // if (selectionSet.length > 1) {
      //   this.$tap.alert('只允许选择关联同一个机会点的合同！')
      //   return
      // }
      this.$set(this.model, 'contractcode', selectKey)
    },
    judgeDecisionUser(newLevel) {
      if (!validateNull(this.model.decisionusercode)) {
        getAction(this.url.judgeDecisionUser, { decisionusercode: this.model.decisionusercode, decisionusername: this.model.decisionusername, newlevel: newLevel }).then((res) => {
          if (res.success) {
            this.$set(this.model, 'decisionusercode', res.result.newdecisionusercode)
            this.$set(this.model, 'decisionusername', res.result.newdecisionusername)
            } else {
              this.$tap.alert(res.message, 'warning')
            }
        })
      }
    }
  },
  created() {
    // 抽屉组件必有
    window.addEventListener('resize', this.resizeHandler)
  },
  destroyed() {
    // 抽屉组件必有
    window.removeEventListener('resize', this.resizeHandler)
  }
}
</script>
<style scoped>
.formLine {
  position: relative;
  margin: 0 auto;
  width: 900px;
  height: 1px;
  background-color: #d4d4d4;
  text-align: center;
  font-size: 16px;
  color: rgba(101, 101, 101, 1);
}
.formLineTitle {
  position: absolute;
  left: 12%;
  font-family: "kaiTi";
  background-color: #ffffff;
  padding: 0 15px;
  transform: translateX(-50%) translateY(-50%);
}
</style>
